package com.cloudy.impl;

import com.cloudy.ec2.response.error.ErrorResponseType;
import com.cloudy.exception.AWSAccessException;
import com.cloudy.exception.EC2AccessException;
import com.cloudy.utility.CloudyUtility;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import java.io.InputStream;
import java.util.logging.Logger;

public class EC2ErrorResponseHandler extends ErrorResponseHandler {
    private Logger logger = Logger.getLogger(this.getClass().getName());
    private JAXBContext ctx;

    public EC2ErrorResponseHandler() {
        try {
            ctx = JAXBContext.newInstance("com.cloudy.ec2.response:com.cloudy.ec2.response.error");
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void handleException(InputStream errorStream)
            throws AWSAccessException {
        Object result = unmarshalTheResponse(errorStream);
        System.out.println("Exc result is " + result);
        ErrorResponseType error = (ErrorResponseType) result;
        throw new EC2AccessException(error);
    }

    @Override
    public Object unmarshalTheResponse(InputStream stream) throws EC2AccessException {
        Object t = null;
        try {
            t = CloudyUtility.unmarshalTheResponse(ctx, stream);
        } catch (Exception e) {
            throw new EC2AccessException(e);
        }
        return t;
    }
}
